﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace PwjCy.Lite.Security.Imp
{
    public class PasswordGenerateService : IPasswordGenerateService
    {
        static byte[] key = new byte[] { 230, 49, 37, 134, 188, 120, 220, 110, 29, 38, 57, 189, 94, 201, 230, 10 };
        static byte[] iv = new byte[] { 98, 132, 149, 73, 41, 18, 210, 22, 101, 92, 183, 175, 190, 120, 200, 198 };
        public string EncryptPassword(string plain, string salt = "pwjcy@#lite")
        {
            try
            {
                SymmetricAlgorithm des = Rijndael.Create();
                byte[] inputByteArray = Encoding.UTF8.GetBytes(plain + salt);
                des.Key = key;
                des.IV = iv;
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                byte[] cipherBytes = ms.ToArray();
                cs.Close();
                ms.Close();
                return Convert.ToBase64String(cipherBytes);
            }
            catch
            {
                return string.Empty;
            }
        }
        public string DecryptPassword(string ciphertext, string salt = "pwjcy@#lite")
        {
            try
            {
                RijndaelManaged rijn = new RijndaelManaged();
                ICryptoTransform trans = rijn.CreateDecryptor(key, iv);
                byte[] data = Convert.FromBase64String(ciphertext);
                MemoryStream ms = new MemoryStream(data);
                CryptoStream cs = new CryptoStream(ms, trans, CryptoStreamMode.Read);
                StreamReader sr = new StreamReader(cs);
                string r_data = string.Empty;
                try
                {
                    r_data = sr.ReadToEnd();
                }
                finally
                {
                    sr.Close();
                }
                return r_data.Substring(0, r_data.Length - salt.Length);
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}
